﻿
#define tweetlist

#define newcode

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Hammock.Web;
using Hammock.Authentication.OAuth;
using System.Xml.Linq;
using System.Windows.Data;
using System.IO.IsolatedStorage;
using Microsoft.Phone;
using System.Security.Cryptography;
using Hammock;

namespace _3dtext1
{
 
    public partial class TextSpace : UserControl
    {
        XElement xmltweets;
        int counter;
        int maxcount;
       //  twsettings TwitterSettings = new twsettings("adI2E0TBaGX0CUxXtHMh6w", "NXIrXrKynAkhdh1EhbSB4jK1e9ebbcmrPdAFX39MEl4", "https://api.twitter.com/oauth/request_token", "http://www.google.com" ,"1.0a" );

        string OAuthTokenKey = string.Empty;
        string tokenSecret = string.Empty;

        string accessToken = string.Empty;
        string accessTokenSecret = string.Empty;

        string userID = string.Empty;
        string userScreenName = string.Empty;

        private List<Text3D> _text3Ds = new List<Text3D>();
        private Canvas _holder = new Canvas();

        public int SPACE_LENGTH = 1000;  // dimension of the 3d space
        public Point3D camera = new Point3D(); // camera
        public Point3D destination = new Point3D(0, 0, -500); // move desination

        private String _allTexts = "0 1 2 3 4 5 6 7 8 9 Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Sd Tt Uu Vv Ww Xx Yy Zz";
        private double _xMul = 10; 		// springness toward x axis
        private double _yMul = 10; 		// springness toward y axis
        private double _zMul = 30;		// springness toward z axis
////        private double _zMovement = 2;	// speed toward z axis
        private double _zMovement = 0;	// speed toward z axis
        public List<agg> aggvar = new List<agg>();
        public agg[] aggvar1 = new agg[100];

        public TextSpace()
        {
            InitializeComponent();
            int temp=0;
            // add the holder to the canvas
            _holder.SetValue(Canvas.LeftProperty, Width / 4);
            _holder.SetValue(Canvas.TopProperty, Height / 4);
            while (temp != 100)
            {
                aggvar1[temp] = new agg();
               temp++;

            }
            LayoutRoot.Children.Add(_holder);


            var oauth = new OAuthWorkflow
            {
                ConsumerKey = TwitterSettings.consumerKey,
                ConsumerSecret = TwitterSettings.consumerKeySecret,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                RequestTokenUrl = TwitterSettings.RequestTokenUri,
                Version = TwitterSettings.oAuthVersion,
                CallbackUrl = TwitterSettings.CallbackUri
            };

            var info = oauth.BuildRequestTokenInfo(WebMethod.Get);
            var objOAuthWebQuery = new OAuthWebQuery(info);
            objOAuthWebQuery.HasElevatedPermissions = true;
            objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
            objOAuthWebQuery.SilverlightMethodHeader = "GET";


            objOAuthWebQuery.RequestAsync(TwitterSettings.RequestTokenUri, null);
            objOAuthWebQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
                //new EventHandler(requestTokenQuery_QueryResponse);// requestTokenQuery_QueryResponse);
            
          

/*

            var client = new RestClient
            {
                Authority = "http://api.twitter.com",
                VersionPath = "1"
            };

            var request = new RestRequest
            {
                Path = "statuses/public_timeline.json"
            };

            var callback = new RestCallback(
                (restRequest, restResponse, userState) =>
                {
                    // Callback when signalled

                    Dispatcher.BeginInvoke(() => actualcallback(restRequest, restResponse, userState));
                    

                }
                );

            client.BeginRequest(request, callback);
           */



        }
        void requestTokenQuery_QueryResponse(Object sender, WebQueryResponseEventArgs e)
        {

            Dictionary<string, string> nameValueCollection = new Dictionary<string, string>();
            string[] items = e.Response.Split('&');

            foreach (string item in items)
            {
                if (item.Contains("="))
                {
                    string[] nameValue = item.Split('=');
                    if (nameValue[0].Contains("?"))
                        nameValue[0] = nameValue[0].Replace("?", "");
                    nameValueCollection.Add(nameValue[0], System.Net.HttpUtility.UrlDecode(nameValue[1]));
                }
            }
             OAuthTokenKey = nameValueCollection["oauth_token"];
             tokenSecret = nameValueCollection["oauth_token_secret"];
            var authorizeUrl = TwitterSettings.AuthorizeUri + "?oauth_token=" + OAuthTokenKey;

            Dispatcher.BeginInvoke(() =>
            {
                this.webBrowser1.Navigate(new Uri(authorizeUrl));
            });
        }
        
        private void objAuthorizeBrowserControl_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
           this.webBrowser1.Visibility = Visibility.Visible;
            this.webBrowser1.Navigated -= objAuthorizeBrowserControl_Navigated;
            
        }
     

        private void objAuthorizeBrowserControl_Navigating(Object sender,System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.ToString().StartsWith(TwitterSettings.CallbackUri))
            {
                
                Dictionary<string, string> AuthorizeResult = new Dictionary<string, string>();
                string[] items = e.Uri.ToString().Split('&');

                foreach (string item in items)
                {
                    if (item.Contains("="))
                    {
                        string[] nameValue = item.Split('=');
                        if (nameValue[0].Contains("?"))
                            nameValue[0] = nameValue[0].Replace("?", "");
                        AuthorizeResult.Add(nameValue[0], System.Net.HttpUtility.UrlDecode(nameValue[1]));
                    }
                }
                var VerifyPin = AuthorizeResult["oauth_verifier"];
                this.webBrowser1.Visibility = Visibility.Collapsed;

                //We now have the Verification pin
                //Using the request token and verification pin to request for Access tokens

                var AccessTokenQuery = GetAccessTokenQuery(
                                                                         OAuthTokenKey,     //The request Token
                                                                         tokenSecret,       //The request Token Secret
                                                                         VerifyPin         // Verification Pin
                                                                        );

                AccessTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(AccessTokenQuery_QueryResponse);
                AccessTokenQuery.RequestAsync(TwitterSettings.AccessTokenUri, null);
            }
        }

        void AccessTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
        {
            try
            {


                Dictionary<string, string> parameters = new Dictionary<string, string>();
                string[] items = e.Response.ToString().Split('&');

                foreach (string item in items)
                {
                    if (item.Contains("="))
                    {
                        string[] nameValue = item.Split('=');
                        if (nameValue[0].Contains("?"))
                            nameValue[0] = nameValue[0].Replace("?", "");
                        parameters.Add(nameValue[0], System.Net.HttpUtility.UrlDecode(nameValue[1]));
                    }
                }
                accessToken = parameters["oauth_token"];
                accessTokenSecret = parameters["oauth_token_secret"];
                userID = parameters["user_id"];
                userScreenName = parameters["screen_name"];

                SetKeyValue<string>("AccessToken", accessToken);
                SetKeyValue<string>("AccessTokenSecret", accessTokenSecret);
                SetKeyValue<string>("ScreenName", userScreenName);

#if newcode
                //newly added for getting friends timeline
                var oauth1 = new OAuthWorkflow
                {

                 //   AccessTokenUrl = new Uri("http://api.twitter.com/1/statuses/friends_timeline.xml?screen_name=sonuthomas").ToString(),
                    ConsumerKey = TwitterSettings.consumerKey,
                    ConsumerSecret = TwitterSettings.consumerKeySecret,
                    SignatureMethod = OAuthSignatureMethod.HmacSha1,
                    Token = accessToken,
                    Version = TwitterSettings.oAuthVersion,
                     TokenSecret=accessTokenSecret,
                     CallbackUrl=TwitterSettings.CallbackUri
                };
               
                
                
                oauth1.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader;
                
                var info = oauth1.BuildProtectedResourceInfo(WebMethod.Get,new WebParameterCollection(),new Uri("http://api.twitter.com/1/statuses/friends_timeline.xml").ToString());
                
                var objOAuthWebQuery = new OAuthWebQuery(info);
                objOAuthWebQuery.HasElevatedPermissions = true;
                objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
                objOAuthWebQuery.SilverlightMethodHeader = "GET";

                objOAuthWebQuery.QueryResponse += new EventHandler<Hammock.Web.WebQueryResponseEventArgs>(friends_data);
                objOAuthWebQuery.RequestAsync(new Uri("http://api.twitter.com/1/statuses/friends_timeline.xml").ToString(), null);
#endif
                //newly added for getting friends timeline
              //  GetUserTimeLine(userScreenName);
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(ex.Message);
                });
            }
        }
        private void friends_data(Object sender, WebQueryResponseEventArgs e)
        {
            if (e.Response!= null)
            {
                 xmltweets = XElement.Parse(e.Response);

#if tweetlist

                Dispatcher.BeginInvoke(() =>
             {
                 listboxMyTimeline.ItemsSource = from tweet in xmltweets.Descendants("status")
                                                 select new titem
                                                 {
                                                     UserName = tweet.Element("user").Element("screen_name").Value,
                                                     Msg = tweet.Element("text").Value,
                                                     Isrc = tweet.Element("user").Element("profile_image_url").Value
                                                 };

                 listboxMyTimeline.Visibility = Visibility.Visible;

             });
#else           
   
   Dispatcher.BeginInvoke(() =>
             {
                addTexts();
             });
#endif 
            }
           
            string[] items = e.Response.Split('&');
        }
        private void GetUserTimeLine(string userName)
        {
            WebClient wcTwitterTimeline = new WebClient();
            wcTwitterTimeline.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wcTwitterTimeline_DownloadStringCompleted);
            wcTwitterTimeline.DownloadStringAsync(new System.Uri("http://api.twitter.com/1/statuses/friends_timeline.xml?screen_name=" + userName));
        }

        void wcTwitterTimeline_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                return; 
            }
            XElement Tweets = XElement.Parse(e.Result);
            //listboxMyTimeline.ItemsSource = from tweet in Tweets.Descendants("status")
            //                                select new titem
            //                                {
            //                                    UserName = tweet.Element("user").Element("screen_name").Value,
            //                                    Msg = tweet.Element("text").Value,
            //                                     Isrc = tweet.Element("user").Element("profile_image_url").Value
            //                                };
            //Dispatcher.BeginInvoke(() =>
            //{
            //    listboxMyTimeline.Visibility = Visibility.Visible;
             
            //});
        }

        private T GetKeyValue<T>(string key)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains(key))
                return (T)IsolatedStorageSettings.ApplicationSettings[key];
            else
                return default(T);
        }

        private void SetKeyValue<T>(string key, T value)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains(key))
                IsolatedStorageSettings.ApplicationSettings[key] = value;
            else
                IsolatedStorageSettings.ApplicationSettings.Add(key, value);
            IsolatedStorageSettings.ApplicationSettings.Save();
        }
        public  OAuthWebQuery GetAccessTokenQuery(string requestToken, string RequestTokenSecret, string oAuthVerificationPin)
        {
            var oauth = new OAuthWorkflow
            {
                AccessTokenUrl = TwitterSettings.AccessTokenUri,
                ConsumerKey = TwitterSettings.consumerKey,
                ConsumerSecret = TwitterSettings.consumerKeySecret,
                ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                Token = requestToken,
                Verifier = oAuthVerificationPin,
                Version = TwitterSettings.oAuthVersion
                
            };

            var info = oauth.BuildAccessTokenInfo(WebMethod.Post);
            var objOAuthWebQuery = new OAuthWebQuery(info);
            objOAuthWebQuery.HasElevatedPermissions = true;
            objOAuthWebQuery.SilverlightUserAgentHeader = "Hammock";
            objOAuthWebQuery.SilverlightMethodHeader = "GET";
            return objOAuthWebQuery;
        }
        void actualcallback(Hammock.RestRequest restRequest,Hammock.RestResponse restResponse,Object userState)
        {
        }
        void text3D_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Text3D text3D = sender as Text3D;

            // set the camera to the position of the text
////            destination.z = text3D.point3D.z + SPACE_LENGTH;
            destination.z = text3D.point3D.z + SPACE_LENGTH + 1;
            destination.y = text3D.point3D.y;
            destination.x = text3D.point3D.x;
        }

        private void postTexts()
        {
            for (int i = 0; i < _text3Ds.Count; i++)
            {
                Text3D text3D = _text3Ds[i];
             
                double zActual = SPACE_LENGTH + (text3D.point3D.z - camera.z);
                double scale = SPACE_LENGTH / zActual;

                if (scale > 0)
                {
                    text3D.x = (text3D.point3D.x - camera.x) * scale;
                    text3D.y = (text3D.point3D.y - camera.y) * scale;

                    ScaleTransform scaleTransform = new ScaleTransform();
                    scaleTransform.ScaleX = scale;
                    scaleTransform.ScaleY = scale;
                    text3D.RenderTransform = scaleTransform;

                    text3D.Opacity = 1 - 0.99 * zActual / SPACE_LENGTH * 0.5;
                }
                else
                {
                    // if text move over the screen, place it at the back
                    text3D.point3D.z += SPACE_LENGTH * 2;
                }
            }
        }

        private void addTexts()
        {
            int seed = (int)DateTime.Now.Ticks;
            counter = 0;
            String[] texts = _allTexts.Split(new Char[] { ' ' });

              foreach(XElement tweet  in xmltweets.Descendants("status"))
            {
                 String limg = tweet.Element("user").Element("profile_image_url").Value;

                String ltxt = tweet.Element("text").Value;
                agg agglvar=  new agg();
                  
                  aggvar1[counter].img =  String.Copy( limg);
                  aggvar1[counter].txt = String.Copy(ltxt);

                  counter++;
                

            }
              maxcount = counter;  
            counter = 0;

            for (int i = 0; i < texts.Length;  i++)
            {
                agg tvar=null;
                seed += (int)DateTime.Now.Ticks;
                Random r = new Random(seed);
                String text = texts[i];
                Text3D text3D = new Text3D();
               // text3D.text.Text = text;


/*
                //Create the source string
                string s = "deal";

                //Create the binding description
                Binding b = new Binding("");
                b.Mode = BindingMode.OneTime;

                b.Source = s;


                text3D.text.SetBinding(TextBlock.TextProperty, b);
               

                */

               
                //Create the binding description
                Binding b = new Binding("");
                b.Mode = BindingMode.OneTime;

                b.Source = aggvar1[counter].txt;


                text3D.text.SetBinding(TextBlock.TextProperty, b);
             
                //Create the binding description
                Binding b1 = new Binding("");
                b1.Mode = BindingMode.OneTime;

                b1.Source = aggvar1[counter].img;


                text3D.image1.SetBinding(Image.SourceProperty, b1);
               
               // text3D.text.Text = aggvar1[counter].txt;
             //   text3D.T3Dimg =  aggvar1[counter].img;
             //   text3D.T3Dimg = "./ApplicationIcon.png";
                //text3D.update("ApplicationIcon.png");

                ////text3D.point3D.x = r.NextDouble() * Width - Width / 2;
                ////text3D.point3D.y = r.NextDouble() * Height - Height / 2;
                ////text3D.x = text3D.point3D.x;
                ////text3D.y = text3D.point3D.y;
                ////text3D.point3D.z = r.NextDouble() * SPACE_LENGTH * 2 - SPACE_LENGTH;
                
                text3D.point3D.x = r.NextDouble() * Width - Width / 2;
                text3D.point3D.y = r.NextDouble() * Height - Height / 2;
                text3D.x = text3D.point3D.x;
                text3D.y = text3D.point3D.y;
                text3D.point3D.z = i * 100 - SPACE_LENGTH;

                text3D.MouseLeftButtonDown += new MouseButtonEventHandler(text3D_MouseLeftButtonDown);
                _holder.Children.Add(text3D);

                _text3Ds.Add(text3D);
 
                if (counter == maxcount)
                    break;



            }
        }

        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            // move the camera automatically
            destination.z += _zMovement;

            camera.z += (destination.z - camera.z) / _zMul;
            camera.x += (destination.x - camera.x) / _xMul;
            camera.y += (destination.y - camera.y) / _yMul;

            // rearrange the position of the texts
            postTexts();
        }

        public void Start()
        {
            
            WebClient tw = new WebClient();
          

            ////            Application.Current.Host.Settings.MaxFrameRate = 24;
            Application.Current.Host.Settings.MaxFrameRate = 30;
            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

            
   //  tw.DownloadStringCompleted += new DownloadStringCompletedEventHandler(tw_dsc);
       //     tw.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + textBox1.Text));
        //  tw.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=udaykishore"));
            //tw.DownloadStringAsync(new Uri("https://api.twitter.com/1/statuses/mentions.rss"));

        
        }
        void tw_dsc(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
               return;

            xmltweets = XElement.Parse(e.Result);
     
            // add all the texts to the stage
            addTexts();

            ////            Application.Current.Host.Settings.MaxFrameRate = 24;
            Application.Current.Host.Settings.MaxFrameRate = 30;
            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);



        }

        private void hi_obj(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.ToString().StartsWith(TwitterSettings.CallbackUri))
            { 

                Dictionary<string, string> AuthorizeResult = new Dictionary<string, string>();
                string[] items = e.Uri.ToString().Split('&');

                foreach (string item in items)
                {
                    if (item.Contains("="))
                    {
                        string[] nameValue = item.Split('=');
                        if (nameValue[0].Contains("?"))
                            nameValue[0] = nameValue[0].Replace("?", "");
                        AuthorizeResult.Add(nameValue[0], System.Net.HttpUtility.UrlDecode(nameValue[1]));
                    }
                }
                var VerifyPin = AuthorizeResult["oauth_verifier"];
                this.webBrowser1.Visibility = Visibility.Collapsed;

                //We now have the Verification pin
                //Using the request token and verification pin to request for Access tokens

                var AccessTokenQuery = GetAccessTokenQuery(
                                                                         OAuthTokenKey,     //The request Token
                                                                         tokenSecret,       //The request Token Secret
                                                                         VerifyPin         // Verification Pin
                                                                        );

                AccessTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(AccessTokenQuery_QueryResponse);
                AccessTokenQuery.RequestAsync(TwitterSettings.AccessTokenUri, null);
            }
        }
    }
    public class TwitterSettings
    {
        public static string RequestTokenUri = "https://api.twitter.com/oauth/request_token";
        public static string AuthorizeUri = "https://api.twitter.com/oauth/authorize";
        public static string AccessTokenUri = "https://api.twitter.com/oauth/access_token";

        public static string CallbackUri = "http://www.google.com";

        public static string StatusUpdateUrl { get { return "http://api.twitter.com"; } }

        //#error TODO REGISTER YOUR APP WITH TWITTER TO GET YOUR KEYS AND FILL THEM IN HERE
        public static string consumerKey = "adI2E0TBaGX0CUxXtHMh6w";
        public static string consumerKeySecret = "NXIrXrKynAkhdh1EhbSB4jK1e9ebbcmrPdAFX39MEl4";

        public static string oAuthVersion = "1.0a";


    } ;
    public class titem
    {
        public string UserName { get; set; }
        public string Msg { get; set; }
        public string Isrc { get; set; }

    }
    public class agg
    {

        public string txt { get; set; }
        public string img { get; set; }
    }
}
